<?php
// $Id$

/**
 * Controller_User 控制器
 */
class Controller_User extends Controller_Abstract
{
	
	function activeKey($user, $password){
		return substr(md5($user.$password."water"), 0, 32);
	}
	
	function mailActive($email, $user, $key){
		$subject = "witpn账户激活邮件";
		$activeUrl = url("user/active", array('key'=>$key, 'user'=>$user));
        $message = "您好{$user}: \n
			您在<a href='www.witpn.com'>witpn网</a>注册了一个账户，基本信息如下：\n
			==============================================\n
			用户名： {$user}\n
			Email地址： {$email}\n
			==============================================\n
			如果您确认无误，请点击如下链接激活：\n
			<a href='$activeUrl'>$activeUrl</a>\n\n
			本邮件由系统自动发出，请勿回复。\n\n
			感谢您的使用
			witpn网";
		                        
		$headers = 'From: ikombat@gmail.com' . "\r\n" . 'Reply-To: ikombat@gmail.com' . "\r\n" .'X-Mailer: PHP/' . phpversion();
		
		return @mail($email, $subject, $message, $headers);
	}
	
	function actionIndex()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
	}
	
	function actionLogin()
	{
		$this->_view['cssfiles'] = array('small');
		$this->_view['location'] = "mine";
		
		if ($this->_context->isPOST())
		{
			if(isset($_POST['username'])){
				$_POST['username'] = strtolower(trim($_POST['username']));
			}else{
				return '{state : "fail", data : "请输入用户名"}';
			}
			if(empty($_POST['password'])){
				return '{state : "fail", data : "请输入密码"}';
			}
			$name = DB::real_escape($_POST['username']);
			$password = sha1($_POST['password']);
			
			$query = "select id, nickname, name, email, actived from user where (name = '$name' or email = '$name') and password = '$password'";
			$res = DB::query($query);
			if($res->num_rows > 0){
				$row = $res->fetch_assoc();
				$actived = $row['actived'];
				if ($actived != '1'){
					$key = $row['actived'];
					if($this->mailActive($name, $row['email'], $key)){
						return '{state: "fail", data: "账户还未激活，激活邮件已经发送到Email,请激活后登陆"}';
					}else{
						return '{state: "fail", data: "账户还未激活，并且激活邮件发送失败，请稍后重试，或者联系我们"}';
					}
				}
				$suer = array();
				$suer['id'] = $row['id'];
				$suer['name'] = $row['name'];
                $susr['nickname'] = $row['nickname'];
				$this->_app->changeCurrentUser($suer, 'member');
				return "{state : 'success'}";
			}else{
				return '{state: "fail", data : "用户名或者密码不正确，请重新输入" }';
				//$this->_view['errMsg'] = "用户名或密码错误，请再试一下:)";
			}
		}else{
			isset($_SERVER['HTTP_REFERER']) and $refer = $_SERVER['HTTP_REFERER'] or $refer = null;
			if (strstr($refer, "register") || strstr($refer, "logout")){
				$refer = null;
			}
			$this->_view['refer'] = (empty($refer) ? url("sec") : $refer);
		}
		
	}
	
	function actionLogout(){
		$this->_view['location'] = "mine";
		
		$this->_view['title'] = '退出';
		$this->_viewname = '../_layouts/default_layout';
		$this->_app->cleanCurrentUser();
		$this->_view['content'] = '<div class="clear" style="padding: 20px"></div>成功退出，谢谢使用WiTPn';
	}
	
	
	/**
	 * 对表单数据进行验证，将验证结果输出到$errMsg中
	 * 返回的$errMsg结果为数组，比如： array('不能为空', '字符太长');
	 *
	 * @param array $errMsg
	 * 
	 * @return bool 是否验证成功, 没有问题返回true,有问题（错误）返回false
	 */
	function checkRegister(& $errMsg){
		//filter
		if(isset($_POST['email'])){
			$_POST['email'] = strtolower(trim($_POST['email']));
		}else{
			$_POST['email'] = "";
		}
		
		if(isset($_POST['username'])){
			$_POST['username'] = strtolower(trim($_POST['username']));
		}else{
			$_POST['username'] = "";
		}
		
		//validation
		$rules = array();
		$rules['email'] = array(
			array('is_email'),
            array('max_iconv_length', 40)
		);
		$rules['username'] = array(
			array('min_length', 1),
			array('max_iconv_length', 24),
            array('is_alnumu')
		);
		
		$rulesMsg= array('email' => array('is_email' => '请输入正确的邮箱，比如: witpns@gmail.com', 'max_iconv_length' => '请输入长度不超过40的邮箱:)'),
					'username' => array( 'not_empty'=>'用户名不能为空', 'max_iconv_length'=> '用户名长度不能超过24', 'is_alnumu' => '用户名只能是英文，数字或者下划线，不要输入中文或其他字符'),
		);
		//如果$_POST中有nickname，那么将nickname也添加到验证列表中
		if(isset($_POST['nickname'])){
		    $_POST['nickname'] = strtolower(trim($_POST['nickname']));
		    $rules['nickname'] = array(
		        array('min_length', 1),
		        array('max_iconv_length', 24)
		        );
		    $rulesMsg['nickname'] = array('min_length' => '用户昵称不能为空', 'max_iconv_length' => '用户昵称 的长度不能超过24');
		}
		
		return parent::formValidate($_POST, $rules, $rulesMsg, $errMsg);
	}
	
	
	function actionRegister()
	{
		$this->_view['location'] = "mine";
		$this->_view['title'] = '用户注册';
		//$this->_view['cssfiles'] = array('small');
		$errMsg = array();
		
		if ($this->_context->isPOST()){
			//如果密码和确认密码不相同，或者密码为空
			if (strlen($_POST['password']) == 0){
				$errMsg['password'][] = '密码不能为空';
			}else if($_POST['password'] !== $_POST['confirmPassword']){
				$errMsg['password'][] = '两次输入密码不相同';
			}

			//如果验证表单失败
			if($this->checkRegister($errMsg)){
				//用户名是否存在
				$user = DB::real_escape($_POST['username']);
				$query = "select count(*) from user where name='$user'";
				
				$res = DB::query($query);
				$row = $res->fetch_assoc();
				if($row['count(*)'] > 0){
					$errMsg['username'][] = '用户名已经被占用，请重新选择一个名字';
				}else{
					try{
						$password = sha1($_POST['password']);
						$email = DB::real_escape($_POST['email']);
						$md5 = $this->activeKey($user, $password);
						$query = "insert into user set name = '$user', nickname = '$user', password = '$password', email = '$email', actived = '$md5', title = '{$user}的主页', register_time=now()";
						DB::query($query);				
						
						if(!$this->mailActive($email, $user, $md5)){
							$content = "<div class='clear' style='padding-top: 2em;'></div>
                        <div class='text-body'>抱歉，向您发送激活邮件失败，请稍后用未激活的账户登录，系统会再次向您发送激活邮件</div>";
						}else{
							$content = "
                        <div class='clear' style='padding-top: 2em;'></div>
                        <div class='text-body'>
                        <span style='font-size: 20px; font-weight: bold'>账户激活Email已经成功发送到这个邮箱<br />
                        <span style='color:#C3480F'>{$user}</span><br />
                        请点击Email中的链接进行激活！激活成功后您便可以正常登陆。</span>
                            </div>";
						}
						
/*						$content = <<<EOT
						<div class="clear" style="padding-top: 2em;"></div>
						<div class="text-body">
						<span style="font-size: 20px; font-weight: bold">注册成功</span><br /><span>成功后您可以：<br />
						1. 报道小新闻<br />
						2. 关注证券<br />
						3. 有自己的界面<br /><br />
						<a href="/user/login" style="font-size: 20px">点击这里进行第一次登录！</a></span>
						</div>
EOT;
*/			
						$this->_view['content'] = $content;
						return;
					}catch(AclUser_DuplicateUsernameException $ex){
						$form['username']->invalidate("您要注册的用户名 {$user->username} 已经存在了");
					
					}
				}
			}
		}
		$this->_view['errMsg'] = $errMsg;
	}
	
	function actionActive(){
		$this->_view['location'] = 'mine';
		$this->_view['title'] = '激活账号';
		
		
	}

    /*
     * 个人信息设置
     */
    function actionSetting(){
        $this->_view['location'] = 'mine';
        //$this->_view['cssfiles'] = array('small');
        $this->_view['title'] = '编辑个人信息';


        $errMsg = array();
        //如果还未登录，先进行登录
        if(!in_array("member", Q::registry('app')->currentUserRoles())){
            return $this->_redirect(url("user/login"));
        }
        
        //如果是提交了数据，则进行验证并修改数据库
        if ($this->_context->isPOST()){
            $unknownError = '<div class="clear" style="padding-top: 2em"></div>
						<span id="redirect"></span>
						未知原因造成的错误，请重新登录后修改<br />';
						
			$id = intval($_POST['id']);
            //如果页面上的id跟用户session中的id不一致，那么返回未知错误
            $user = Q::registry("app")->currentUser();
            if ($id != $user['id']){
			    $this->_view['content'] = $unknownError;
			    return ;
            }
            
            if (strlen($_POST['password']) == 0){
                //如果密码部分为空，则不进行密码修改
                $passwdStr = "";
            }else{
                //否则进行密码部分判断，成功后修改密码
                if($_POST['password'] == $_POST['confirmPassword']){
                    $password = sha1($_POST['password']);
                    $passwdStr = " password = '$password', ";
                }else{
                    $errMsg['password'] = '两次输入密码不一致';
                }
            }
            
			//如果验证数据通过
            if($this->checkRegister($errMsg)){
                
                
                $user = DB::real_escape($_POST['username']);
                $nickname = DB::real_escape($_POST['nickname']);
                
                //查找用户名是否已经被其他用户占用
				$query = "select count(*) from user where name='$user' and id != $id ";
				$res = DB::query($query);
				$row = $res->fetch_assoc();
				if($row['count(*)'] > 0){
					$errMsg['username'][] = '用户名已经被占用，请重新选择一个名字';
				}else{
					try{
						//更新数据库中个人信息
						$email = DB::real_escape($_POST['email']);
						$query = "update user set  
							nickname = '$nickname', $passwdStr 
							email = '$email' where id = $id";
						DB::query($query);
						
						$content = <<<EOT
						<div class="clear" style="padding-top: 2em"></div>
						<span id="redirect"></span>
						个人信息修改成功<br />
EOT;
						//显示修改成功
						$this->_view['content'] = $content;
						return;
					}catch(Exception $e){
						return $unknownError;
					}
                }
            }else{
            	//验证数据没有通过
            }
            $this->_view['row'] = $_POST;
        }else{
        //如果没有POST提交，表示要显示“个人信息页面"
        	$user = Q::registry("app")->currentUser();
        	$id = $user['id'];
            $query = "select id, nickname, name as username, email
                 from user
                 where {$id} = user.id
                 limit 1";
            $res = DB::query($query);
            
            //如果找不到相关的信息，则要求重新登录
            if (DB::num_rows() == 0){
            	$this->_app->cleanCurrentUser();
            	return $this->_redirect(url("user/login"));
            }
            $row = $res->fetch_assoc();
            $this->_view['row']=$row;
        }
        
        $this->_view['errMsg'] = $errMsg;
    }
}


